﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;

namespace ConfigurationResource.Domain
{
    public class DataFactory
    {
        public static IConfigurationStore CreateStore()
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            // get assembly file path
            try
            {
                Assembly thisAssembly = Assembly.GetExecutingAssembly();
                string strLoc = thisAssembly.CodeBase;
                strLoc = strLoc.Replace("file:///", "");

                int check = 0;
                int nFinal = 0;
                string strParse = strLoc;
                while (check != -1)
                {
                    check = strParse.IndexOf("/", check + 1);
                    if (check != -1)
                    {
                        nFinal = check;
                    }

                }
                strLoc = strLoc.Substring(0, nFinal + 1);

                // get Data Store information
                string strTargetAssembly = appSettings.Get("Configuration.DataStore.Assembly");
                string strTargetType = appSettings.Get("Configuration.DataStore.Assembly.Type");

                // create instance of assembly for store
                Assembly providerAsm = Assembly.LoadFrom(strLoc + strTargetAssembly + ".dll");
                Type typ = providerAsm.GetType(strTargetType);
                return (IConfigurationStore)Activator.CreateInstance(typ);
            }
            catch (ConfigurationErrorsException cee)
            {
                EventLog myLog = new EventLog();
                myLog.Log = appSettings.Get("Configuration.EventLog.Log");
                myLog.Source = appSettings.Get("Configuration.EventLog.Source");
                myLog.WriteEntry("\nConfiguration Files are not set up properly (DataFactory.CreateStore). Message from Microsoft: \n" + cee.StackTrace + cee.Message, EventLogEntryType.Error);
                return null;
            }
            catch (Exception ex)
            {
                EventLog myLog = new EventLog();
                myLog.Log = appSettings.Get("Configuration.EventLog.Log");
                myLog.Source = appSettings.Get("Configuration.EventLog.Source");
                myLog.WriteEntry("\nCould not create data store (DataFactory.CreateStore). Message from Microsoft: \n" + ex.StackTrace + ex.Message, EventLogEntryType.Error);
                return null;
            }
        }


    }
}